<template>
	<view>
		<!-- 主体 -->
		<view class="page page-bottom-bar book-hotel">
			<!-- 入住信息 -->
			<view class="book-info p25">
				<view class="font15">{{billInfo.hotel ? billInfo.hotel.name : ''}}</view>
				<view class="font13">
					<image class="icon-date" mode="widthFix"
						src="https://static.newbeaconhotels.com/app/hotel/icon-date.png"></image>
					<text class="font-969696">入住：</text><uni-dateformat class="format" :date="calendar.startDate"
						format="yyyy-MM-dd"></uni-dateformat>
					<text class="font-969696">离店：</text><uni-dateformat class="format" :date="calendar.endDate"
						format="yyyy-MM-dd"></uni-dateformat>
					<text class="font-969696">共{{calendar.dayCount}}晚</text>
				</view>
				<view class="font13 font-969696">
					<image class="icon-lan" mode="widthFix"
						src="https://static.newbeaconhotels.com/app/hotel/icon-lan.png"></image>
					<text>{{billInfo.hotel ? billInfo.hotel.addrd : ''}}</text>
				</view>
			</view>
			<view class="hr7"></view>
			<!-- 订单信息 -->
			<view class="book-detail font14">
				<view class="item">
					<view>{{roomName}}</view>
					<uni-number-box v-model="form.rmnum" :min="1" :max="maxRoomNum"
						@change="roomNumChange"></uni-number-box>
				</view>
				<view class="item" @click="Onman">
					<view>入住人</view>
					<view>{{form.rsvman}}　{{form.mobile}}<uni-icons type="arrowright" size="10"
							color="#3f3f3f"></uni-icons></view>
				</view>
				<view class="item" @tap="openBreakfast">
					<view>早餐份数</view>
					<view :style="{color: breakfast.selected ? '#1e1e1e' : (billInfo.num ? '#ff0000' : '#c8c8c8')}">
						<text>{{breakfast.selected ? breakfast.selected.name : (billInfo.num ? billInfo.num + '种早餐可供选择' : '无可用早餐')}}</text>
						<uni-icons type="arrowright" size="10" color="#3f3f3f"></uni-icons>
					</view>
				</view>
				<view class="item nob">
					<view>支付方式</view>
					<uni-data-checkbox v-model="payType.value" :localdata="payType.range" :selectedColor="themeColor"
						selectedTextColor="#1e1e1e" @change="payChange">
					</uni-data-checkbox>
				</view>
				<view v-if="form.channel != 'YHHD'" class="item" @tap="openCoupon">
					<view>优惠券</view>
					<view :style="{color: coupon.selected ? '#1e1e1e' : (billInfo.coupon ? '#ff0000' : '#c8c8c8')}">
						<text>{{coupon.selected ? ('-￥' + coupon.selected.reduce_money) : (billInfo.coupon ? billInfo.coupon + '张优惠券可用' : '无可用优惠券')}}</text>
						<uni-icons type="arrowright" size="10" color="#3f3f3f"></uni-icons>
					</view>
				</view>
			</view>
			<view class="hr7"></view>
			<!-- 发票信息 -->
			<view class="book-memo p25">
				<view class="font12 font-assist">*发票信息 如需办理发票，可去前台办理</view>
				<textarea :value="form.remark" @input="Onremark" placeholder="请输入备注内容"
					placeholder-class="placeholderClass"></textarea>
			</view>
			<view class="hr7"></view>
			<!-- 说明 -->
			<view class="book-tip p25">
				<view class="font13 font-646464">说明：</view>
				<view class="nodes font11 font-646464">
					<rich-text :nodes="billInfo.hotel ? billInfo.hotel.explain : ''"></rich-text>
				</view>
			</view>
		</view>

		<!-- 早餐弹窗 -->
		<uni-popup ref="breakfast" type="bottom" :maskClick="false">
			<view class="picker_bos">
				<view class="title flex-row-between">
					<view class="title_qx" @click="closeBreakfast">取消</view>
					<view class="title_qd" @click="onBreakfast">确定</view>
				</view>
				<view class="picker_box">
					<template v-for="(item, index) in breakfast.list">
						<view class="check-box flex-row-start" :key="index"
							:class="{ checked: item.id == breakfast.current.id }" @click="breakfastChange(item)">
							<view class="inner"></view>
							<text class="info">{{item.name}}</text>
						</view>
					</template>
				</view>
			</view>
		</uni-popup>

		<!-- 优惠券弹窗 -->
		<bottomPopup ref="coupon" title="选择优惠券" :btnMargin="'60rpx auto;'">
			<scroll-view :scroll-y="true" v-if="coupon.list && coupon.list.length > 0" class="popup-coupons">
				<view class="coupon-item flex-row-start" v-for="(item, index) in coupon.list" :key="index">
					<view class="left flex-column-center">
						<view class="tag">{{item.coupon_type_name}}</view>
						<view class="font12 font-assist">
							<!-- 10满减卷 30立即卷 -->
							<text v-if="item.coupon_type==10 || item.coupon_type==30">￥</text>
							<text v-if="item.coupon_type==10 || item.coupon_type==30"
								class="dis">{{item.reduce_money}}</text>
							<!-- 20折扣卷 -->
							<text v-if="item.coupon_type==20" class="dis">{{item.discount*10}}折</text>
						</view>
					</view>
					<view class="right flex-column-between">
						<view class="font13">{{item.title}}</view>
						<!-- 10满减卷 -->
						<view v-if="item.coupon_type==10" class="font12 font-assist">满{{item.full_money}}使用</view>
						<!-- 20折扣卷 30立即卷 -->
						<view v-if="item.coupon_type==20 || item.coupon_type==30" class="font12 font-assist">无限制</view>
						<view class="font12 font-969696">有效期至{{item.end_time}}</view>
					</view>
					<view @click="Onreduce(item)" class="get font12 font-ffffff tc">{{ item.choois ? '取消使用' : '立即使用'}}
					</view>
				</view>
			</scroll-view>
			<view v-else class="content coupon-empty">
				<image class="img" src="https://static.newbeaconhotels.com/app/hotel/empty.png"></image>
				<view class="txt font13 font-969696 tc">暂无优惠券</view>
			</view>
		</bottomPopup>

		<!-- 合计信息 -->
		<view class="book-bar flex-row-between flex-start">
			<view class="part1 flex-column-center flex-start">
				<view class="font12">订单金额: <text
						class="font16 font-assist">￥{{coupon.selected ? c_total : billInfo.total}}</text></view>
				<view class="font11 font-assist">已优惠￥{{billInfo.discount}}</view>
			</view>
			<view class="part2" @tap="openDetails">
				<text class="font11">明细</text>
				<uni-icons type="arrowup" size="10" color="#424141"></uni-icons>
			</view>
			<view class="btn tc font15 font-ffffff" @click="submit">提交订单</view>
		</view>

		<!-- 订单明细 -->
		<bottomPopup ref="details" title="订单明细">
			<view class="details-box">
				<view v-if="billInfo.price" class="list">
					<block v-for="(item, index) in billInfo.price.daily" :key="index">
						<view class="flex-row-between font14 font-969696">
							<view class="">{{item.date}}</view>
							<view class="">￥{{item.realRate}}</view>
						</view>
					</block>
				</view>
				<view class="price font14 font-969696">
					<view class="">早餐金额：<text class="font-assist">￥{{billInfo.breakfast}}</text></view>
					<view class="">优惠金额：<text class="font-assist">￥{{billInfo.discount}}</text></view>
					<view class="">订单合计：<text class="font-assist">￥{{coupon.selected ? c_total : billInfo.total}}</text>
					</view>
				</view>
			</view>
		</bottomPopup>

		<!-- 确认弹窗 -->
		<uni-popup ref="confirm" type="center">
			<view class="popup-prize">
				<view class="title font15 tc font-b">订单确认</view>
				<view class="content">
					<view class="font14 font-ff3c37 tc">
						<text v-if="form.channel == 'YT'">卡类型：{{billInfo.card}}；</text>
						<text>订单总额：￥{{coupon.selected ? c_total : billInfo.total}}</text>
					</view>
					<view class="font12 font-969696">在线支付订单整晚保留，18:00前可取消（特惠折扣除外）；到店付订单保留至当天18:00</view>
				</view>
				<view class="flex-row-between">
					<view class="btn btn1" @click="cancel">取消</view>
					<view class="btn btn2" @click="confirm">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import Compicker from "@/components/j-Compicker/index.vue";
	import bottomPopup from "@/components/j-bottomPopup/index.vue";
	export default {
		components: {
			Compicker,
			bottomPopup
		},
		data() {
			return {
				themeColor: '#03004c',
				isLogin: false, // 是否已成功获取用户信息
				billInfo: {
					total: '0.00',
					discount: '0.00',
					num: 0,
					coupon: 0
				}, // 账单信息
				c_total: '', // 使用优惠券后的总金额
				calendar: {
					startDate: '',
					endDate: '',
					dayCount: ''
				}, // 日期
				maxRoomNum: 10, // 最大预订数
				roomName: '', // 房间名称
				breakfast: {
					current: null,
					selected: null,
					list: []
				}, // 早餐
				// 优惠券
				coupon: {
					selected: null,
					list: []
				},
				// 支付类型
				payType: {
					value: '2',
					range: [{
							value: '1',
							text: "到店支付"
						},
						{
							value: '2',
							text: "线上支付"
						}
					]
				},
				form: {
					hotel_id: '',
					date: '',
					day_count: '',
					room_id: '',
					rmnum: 1,
					rsvman: '',
					mobile: '',
					channel: '',
					type: '2',
					packages_id: '',
					coupon_order_id: '',
					remark: '',
					os: this.group == 'wxapp' ? 'WxApp' : 'H5'
				},
				// 支付
				h5share: true, // 当前页面是否单独获取签名
				wxSdk: false, // H5签名是否成功（此页面用于唤起支付）
				openid: null,
				wx_code: '',
			}
		},
		onLoad: function(options) {
			// 从缓存中拿取查询条件
			let JsonData = uni.getStorageSync('bookQuery')
			if (JsonData) {
				if (JsonData.calendar) {
					this.calendar = JsonData.calendar
					this.form.date = this.$base.formatTime(new Date(JsonData.calendar.startDate), 'yyyy-MM-dd')
					this.form.day_count = JsonData.calendar.dayCount
				}
				if (JsonData.hotel_id) {
					this.form.hotel_id = JsonData.hotel_id
				}
				if (JsonData.room_id) {
					this.form.room_id = JsonData.room_id
				}
				if (JsonData.room_name) {
					this.roomName = JsonData.room_name
				}
				if (JsonData.channel) {
					this.form.channel = JsonData.channel
				}
			}

			// 获取用户信息
			this.$Http({
				url: 'user',
				token: true
			}).then(res => {
				if (res.code == 1) {
					this.isLogin = true
					this.form.rsvman = res.data.user.name
					this.form.mobile = res.data.user.mobile

					// 获取账单
					this.getBill()
				} else {
					uni.showToast({
						title: res.msg,
						icon: none
					})
				}
			});

			// 早餐列表
			this.getBreakfast()

			// 开启监听选择联系人
			uni.$on('chooseMan', (res) => {
				this.form.rsvman = res.name
				this.form.mobile = res.mobile

				// 清空选择的券
				this.coupon.selected = null
				this.form.coupon_order_id = ''

				// 获取账单
				this.getBill()
			})
		},
		onUnload() {
			// 关闭监听选择联系人
			uni.$off('chooseMan')
		},
		onShow() {
			// #ifdef MP-WEIXIN
			wx.login({
				success: res => {
					this.wx_code = res.code
				}
			})
			// #endif

			// #ifdef H5
			this.$wxapi.OnwxSdk().then(res => {
				if (res.code == 1) {
					this.wxSdk = true
					this.Onshare()
				} else {
					this.wxSdk = false
				}
			})
			this.openid = uni.getStorageSync("openid");
			// #endif
		},
		methods: {
			// 房间数change
			roomNumChange(e) {
				if (parseInt(e) >= this.maxRoomNum) {
					uni.showToast({
						title: '超出预订房间数',
						icon: 'none'
					});
					return
				}

				this.form.rmnum = parseInt(e)

				if (this.form.rmnum >= 3) {
					this.payType = {
						value: '2',
						range: [{
							value: '2',
							text: "线上支付"
						}]
					}
					this.form.type = '2'
				} else {
					this.payType.range = [{
							value: '1',
							text: "到店支付"
						},
						{
							value: '2',
							text: "线上支付"
						}
					]
				}

				// 清空选择的券
				this.coupon.selected = null
				this.form.coupon_order_id = ''

				if (this.isLogin) {
					// 获取账单
					this.getBill()
				}
			},
			// 获取下单可用的券
			getRoomCoupon() {
				this.$Http({
					url: 'roomCoupon',
					token: true,
					data: {
						room_id: this.form.room_id,
						price: this.billInfo.price.total,
						type: this.payType.value == '1' ? '20' : '10',
						channel: '1'
					}
				}).then(res => {
					if (res.code == 1) {
						this.coupon.list = res.data
					}
				});
			},
			// 早餐列表
			getBreakfast() {
				let $this = this;
				this.$Http({
					url: 'packages',
					data: {
						id: $this.form.hotel_id
					},
				}).then(res => {
					if (res.code == 1) {
						$this.breakfast.list = res.data
					} else {
						uni.showToast({
							title: res.msg,
							icon: none
						})
					}
				});
			},
			// 打开早餐
			openBreakfast() {
				this.$refs.breakfast.open()
			},
			// 关闭早餐
			closeBreakfast() {
				this.$refs.breakfast.close()
			},
			// 选择早餐
			breakfastChange(item) {
				this.breakfast.current = item
			},
			// 确认早餐
			onBreakfast() {
				this.$refs.breakfast.close()

				this.breakfast.selected = this.breakfast.current
				this.form.packages_id = this.breakfast.current.id

				// 清空选择的券
				this.coupon.selected = null
				this.form.coupon_order_id = ''

				// 获取账单
				this.getBill()
			},
			// 打开优惠券
			openCoupon() {
				this.$refs.coupon.Onopen()
			},
			//使用优惠券
			Onreduce(e) {
				let list = this.coupon.list
				list.forEach(item => {
					if (item.id == e.id) {
						//不使用
						if (e.choois) {
							item.choois = false
							this.coupon.selected = null
							this.form.coupon_order_id = ''

							this.c_total = this.billInfo.total
							this.billInfo.discount = 0
						} else {
							//使用
							item.choois = true
							this.coupon.selected = item
							this.form.coupon_order_id = item.id

							let result = 0

							// 满减和立减
							if (item.coupon_type == 10 || item.coupon_type == 30) {
								result = this.$base.numSub(this.billInfo.total, item.reduce_money)
							}
							// 折扣
							if (item.coupon_type == 20) {
								result = this.$base.numMulti(this.billInfo.total, item.discount)
								let diff = this.$base.numSub(this.billInfo.total, result)
								item.reduce_money = diff
							}

							this.c_total = (result <= 0 ? '0.00' : result)
							this.billInfo.discount = item.reduce_money
						}
					} else {
						item.choois = false
					}
				})
				this.coupon.list = list
				this.$refs.coupon.onClose()
				// 强制刷新数据
				this.$forceUpdate()
			},
			// 支付方式change
			payChange(e) {
				this.form.type = e.detail.value

				// 清空选择的券
				this.coupon.selected = null
				this.form.coupon_order_id = ''

				// 获取账单
				this.getBill()
			},
			// 打开明细
			openDetails() {
				this.$refs.details.Onopen()
			},
			// 备注
			Onremark(e) {
				this.form.remark = e.detail.value
			},
			// 选择联系人
			Onman() {
				uni.navigateTo({
					url: '/pages/my/contactList?mode=choose'
				});
			},
			// 获取账单
			getBill() {
				this.$Http({
					url: 'orderBill',
					token: true,
					load: true,
					data: this.form
				}).then(res => {
					if (res.code == 1) {
						this.billInfo = res.data

						// 下单券
						this.getRoomCoupon()
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				});
			},
			// 提交表单
			submit() {
				this.form.packages_id = this.breakfast.selected ? this.breakfast.selected.id : ''
				this.$refs.confirm.open()
			},
			// 弹窗取消
			cancel() {
				this.$refs.confirm.close()
			},
			// 弹窗确定订单
			confirm() {
				let that = this;

				this.$refs.confirm.close()
				console.log(this.form, 'asdasd')
				// this.form.date = '2023-03-15'
				// this.form.day_count = 0
				// return
				this.$Http({
					url: 'orderAdd',
					type: 'POST',
					token: true,
					load: true,
					data: this.form
				}).then(res => {

					// 重新获取code
					// #ifdef MP-WEIXIN
					wx.login({
						success: res1 => {
							that.wx_code = res1.code
						}
					})
					// #endif

					if (res.code == 1) {
						// 到店支付
						if (this.payType.value == '1') {
							uni.showToast({
								title: '下单成功'
							});
							setTimeout(() => {
								uni.switchTab({
									url: '/pages/hotel/orderList'
								});
							}, 2000)
						}
						// 线上支付，获取支付参数
						if (this.payType.value == '2') {
							let $obj = {
								type: 'hotel',
								order_id: res.data,
								os: this.group == 'wxapp' ? 'WxApp' : 'H5'
							}
							// #ifdef H5
							$obj.openid = this.openid
							// #endif
							// #ifdef MP-WEIXIN
							$obj.code = this.wx_code
							// #endif
							this.$Http({
								url: 'paySign',
								data: $obj,
							}).then(res1 => {
								if (res1.code == 1) {
									this.Onpay(res1.data)
								} else {
									uni.showToast({
										title: res1.msg,
										icon: 'none'
									});
								}
							});
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				});
			},
			// 支付
			Onpay(param) {
				var that = this
				// #ifdef MP-WEIXIN
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: param.timeStamp,
					nonceStr: param.nonceStr,
					package: param.pacKage,
					signType: 'MD5',
					paySign: param.paySign,
					success: function(res) {
						uni.showToast({
							title: '支付成功'
						});
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/hotel/orderList'
							})
						}, 2000)
					},
					fail: function(err) {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});

						// 吐券
						that.$Http({
							url: 'spit',
							token: true,
							data: {
								wx_order: param.order
							},
						}).then(res => {});
					}
				});
				// #endif
				// #ifdef H5
				if (that.wxSdk) {
					this.$wxapi.OnWXPay(param).then(res => {
						console.log('OnWXPay返回：' + JSON.stringify(res))
						if (res.code == 1) {
							uni.showToast({
								title: '支付成功'
							});
							setTimeout(() => {
								uni.switchTab({
									url: '/pages/hotel/orderList'
								})
							}, 2000)
						} else if (res.code == 0) {
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							});

							// 吐券
							that.$Http({
								url: 'spit',
								token: true,
								data: {
									wx_order: param.order
								},
							}).then(res => {});
						} else if (res.code == 3) {
							uni.showToast({
								title: '支付取消',
								icon: 'none'
							});

							// 吐券
							that.$Http({
								url: 'spit',
								token: true,
								data: {
									wx_order: param.order
								},
							}).then(res => {});
						}
					})
				} else {
					uni.showToast({
						title: '微信签名失败',
						icon: 'none'
					});
				}
				// #endif
			}
		}
	}
</script>

<style lang="less" scoped>
	@import url("style.less");

	.picker_bos {
		width: 750rpx;
		height: 600rpx;
		background-color: #fff;
		border-radius: 10rpx 10rpx 0 0;
		overflow: hidden;

		.title {
			height: 80rpx;
			padding: 0 60rpx;
			border-bottom: 2rpx solid #f5f5f5;
			font-size: 30rpx;

			.title_qx {
				color: #969696;
			}

			.title_qd {
				color: @theme-color;
			}
		}

		.picker_box {
			width: 750rpx;
			height: calc(100% - 80rpx);
			padding: 70rpx 0 0 70rpx;

			.check-box {
				margin-bottom: 50rpx;

				.inner {
					border-radius: 50%;
				}
			}
		}
	}
</style>